package com.tim.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.tim.stack.impl.Stack;

public class Main {
	private static final String QUIT_COMMAND = "q";
	private static final String HELP_COMMAND = "?";
	private static final String HELP = "push <argument>\t\tpushes element(argument) to stack"
			+ "\npop\t\t\ttakes last element from stack"
			+ "\nprint\t\t\tprints all elements in stack" + "\nq\t\t\texit";
	private static final String WARNING = "WRONG COMMAND OR ARGUMENT!\n Use '?' to see help information";

	// TODO handle exceptions
	// TODO readability
	// TODO create parser which will store cmd and arguments 
	public static void main(String[] args) throws IOException,
			SecurityException, NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Stack<String> stack = new Stack<String>();
		/*
		 * for (String s : args) { stack.push(s); } stack.print();
		 * System.out.println(stack.pop()); stack.print();
		 * System.out.println(stack.pop()); stack.print();
		 * System.out.println(stack.pop()); stack.print();
		 * System.out.println(stack.pop()); stack.print();
		 */
		System.out.println("Input 'q' to exit");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String line = null;
		String cmd = null;
		String[] lineArgs = null;
		Method method = null;
		while (true) {
			line = br.readLine();
			if (QUIT_COMMAND.equalsIgnoreCase(line)) {
				break;
			} else if (HELP_COMMAND.equals(line)) {
				System.out.println(HELP);
				continue;
			}

			lineArgs = line.split(" ");
			cmd = lineArgs[0];
			try {
				if (lineArgs.length > 1) {
					method = Stack.class.getMethod(cmd, Object.class);
					method.invoke(stack, lineArgs[1]);
				} else {
					method = Stack.class.getMethod(cmd);
					method.invoke(stack);
				}
			} catch (NoSuchMethodException nsme) {
				System.out.println(WARNING);
			}
		}
	}
}
